/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.tedu.mall.sso.security.service.user;

import cn.tedu.mall.common.pojo.ums.model.User;
import cn.tedu.mall.sso.mapper.user.UserMapper;
import cn.tedu.mall.sso.pojo.domain.UserUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@Slf4j
/**
 * 利用电话号码查询用户信息
 */
public class UserPhoneSSOUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String phoneNum) throws UsernameNotFoundException {
        //先使用mapper查询用户
        User user = userMapper.findByPhone(phoneNum);
        if (user == null) {
            //说明这个手机号没有用户注册，使用游客身份
            user = generateGuest(phoneNum);
        }
        // 检查管理员是否启用
        if (user.getEnable() != 1) {
            throw new BadCredentialsException("登录失败，用户账号已经被禁用！");
        }
        UserUserDetails userDetails = new UserUserDetails();
        BeanUtils.copyProperties(user, userDetails);
        // 返回
        return userDetails;
    }

    private User generateGuest(String phoneNum) {
        User user = new User();
        user.setAvatar("default");
        user.setEmail("default");
        user.setEnable(1);
        user.setPhone(phoneNum);
        user.setUsername(phoneNum);
        user.setPassword("123456");
        user.setNickname(phoneNum);
        return user;
    }

}
